package com.sinaapp.gavinzhang.ConcurrentProgramming;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * 使用ThreadPoolExecutor的invokeAny方法获取最先完成的任务
 * 使用ThreadPoolExecutor的invokeAll方法获取全部任务
 * Created by gavin on 15-9-4.
 */
public class CallableTest {
    public static void main(String[] args)
    {
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
        List<Callable<String>> list = new ArrayList<Callable<String>>();
        for (int i = 0; i < 10; i++) {
            list.add(new CallableTask());
        }
        try {
            String message = threadPoolExecutor.invokeAny(list);
            System.out.println(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        List<Future<String>> flist;
        try {
            flist = threadPoolExecutor.invokeAll(list);
            for (int i = 0; i < flist.size(); i++) {
                Future<String> f = flist.get(i);
                System.out.println(f.get());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
    }
}

class CallableTask implements Callable<String>{
    public String call() throws Exception {
        String message = Thread.currentThread().getName()+"finish";
        Thread.sleep(new Random().nextInt(5000));

        return message;
    }
}
